package com.motu.monstercity.server.game.web;

import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message.Builder;
import com.googlecode.protobuf.format.JsonFormat;
import com.motu.monstercity.protocol.CmdEnum.EnumCmdID;
import com.motu.vertx.module.utility.mysql.MysqlClient;
import com.motu.vertx.module.utility.mysql.MysqlTool;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import com.motu.vertx.module.utility.webtool.BaseWebHandler;
import io.vertx.core.CompositeFuture;
import io.vertx.core.Future;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.client.WebClient;

import java.util.Base64;

public class Errorcode2Handler extends BaseWebHandler {
    public static void search(RoutingContext routingContext, JsonObject json, String adminName, WebClient client){
        HttpServerResponse response = routingContext.response();
        JsonArray params1 = new JsonArray();
        String whereStr = "";
        if (json.containsKey("errcode")) {
            whereStr += " and err_code =? ";
            params1.add(json.getString("errcode"));
        }
        if (json.containsKey("cmd")) {
            whereStr += " and cmd =? ";
            params1.add(json.getString("cmd"));
        }
        if (json.containsKey("userid")) {
            whereStr += " and user_id =? ";
            params1.add(json.getLong("userid"));
        }
        if (json.containsKey("stime")) {
            whereStr += " and add_time >= ? ";
            params1.add(TimeUtils.getTimeStrIntValue(json.getString("stime")));
        }
        if (json.containsKey("etime")) {
            whereStr += " and add_time <= ? ";
            params1.add(TimeUtils.getTimeStrIntValue(json.getString("etime")));
        }

        String sql1 = "select count(1) as total from error_code where 1=1 " + whereStr + ";";
        String sql2 = "select * from error_code where cmd_code >70100 " + whereStr + " order by add_time desc limit ?, ?;";
        JsonArray params2 = params1.copy();
        int pageNo = json.getInteger("pageNo");
        int pageSize = json.getInteger("pageSize");
        int start = pageNo*pageSize;
        params2.add(start);
        params2.add(pageSize);

        Future<JsonArray> fut1 = MysqlTool.queryJsonArrayFromDb(MysqlClient.getServerPool(), sql1, params1);
        Future<JsonArray> fut2 = MysqlTool.queryJsonArrayFromDb(MysqlClient.getServerPool(), sql2, params2);
        CompositeFuture.all(fut1, fut2).onComplete(res->{
            if (res.succeeded()) {
                JsonObject result = new JsonObject();
                int total = fut1.result().getJsonObject(0).getInteger("total");
                result.put("total", total);
                JsonArray list = fut2.result();
                parseToJson(list);  //解析为json字符串
                result.put("rows",list);
                sendHttpResponse(response, result);
            } else {
                sendHttpResponseError(response,  res.cause().getMessage());
            }
        });
    }

    /*
     * 解析为json字符串
     */
    private static void parseToJson(JsonArray list) {
        int max = list.size();
        for (int i=0; i<max; i++) {
            JsonObject obj = list.getJsonObject(i);
            int cmdCode = obj.getInteger("cmd_code");
            String cmdName = obj.getString("cmd");
            String requestJson = "{}";
            try {
                byte[] requestData = Base64.getDecoder().decode(obj.getBinary("request"));
                if (cmdCode > 0 && requestData.length > 0) {
                    EnumCmdID eId1 = EnumCmdID.forNumber(cmdCode);
                    String cmdName1 = eId1.name();
                    int type = cmdName.equals("CMD_DEFAULT") ? 0 : cmdName.contains("CMD_GAME") ? 0 : 1;

                    Builder res_build1 = ProtobufManager.getRequestBuild(cmdName1, type);
                    res_build1.mergeFrom(requestData);
                    requestJson = JsonFormat.printToString(res_build1.build());
                }
            } catch (Exception e) {
                System.out.println("###error cmd:" + cmdCode + " " + cmdName + " name:" + cmdName);
                // TODO 自动生成的 catch 块
            } finally {
                list.getJsonObject(i).put("request", requestJson);
            }
        }
    }
}
